package com.csr;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;
 

public class TabMain extends TabActivity implements OnTabChangeListener
{
  
	TabHost tabHost;
	TabHost.TabSpec spec;
 	Intent intent; 
    Resources res;
    ProgressDialog pd=null;
	Handler handler=new Handler();
	MD5Generator md5Generator=new MD5Generator();
	HttpConn httpConn=new HttpConn();
	MyAccountInfo myAccountInfo;
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
    	super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//		WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
        setContentView(R.layout.tablayout);
        
        res = getResources(); 
        tabHost = getTabHost();
        
        intent = new Intent().setClass(this,MenuActivity.class);
        spec = tabHost.newTabSpec("Home").setIndicator("")
                .setContent(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        tabHost.addTab(spec);
        
        intent = new Intent().setClass(this,FavouriteTab.class);
        spec = tabHost.newTabSpec("Favourite").setIndicator("")
                .setContent(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        tabHost.addTab(spec); 
        
        intent = new Intent().setClass(this,MenuActivity.class);
        spec = tabHost.newTabSpec("Balance").setIndicator("")
                       .setContent(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        tabHost.addTab(spec);
        tabHost.setCurrentTab(0);
        
        tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.home_active);
        tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.favourite);
        tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.balance);
        tabHost.setOnTabChangedListener(this);

    }
	public void onTabChanged(String tabName) 
	{
		if(tabName.equalsIgnoreCase("Home"))
		{
			tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundResource(R.drawable.home_active);
			tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.favourite);
		    tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.balance);
		}
		else if(tabName.equalsIgnoreCase("Favourite"))
		{
			tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundResource(R.drawable.favourite_active);
			tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.home);
		    tabHost.getTabWidget().getChildAt(2).setBackgroundResource(R.drawable.balance);
		}
		else if(tabName.equalsIgnoreCase("Balance"))
		{
			tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundResource(R.drawable.balance_active);
			tabHost.getTabWidget().getChildAt(0).setBackgroundResource(R.drawable.home);
		    tabHost.getTabWidget().getChildAt(1).setBackgroundResource(R.drawable.favourite);
		    pd=ProgressDialog.show(TabMain.this,"please wait.",null);
	        pd.setContentView(R.layout.progress);
	        Thread thread=new Thread(getPersonalInfo);
	        thread.start();
		}
				
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		//Code Comes here.....
       	System.out.println("Key Event:"+event.getAction()+",keyCode"+keyCode);
        onBackPressed();
        return true; 
	}
	 
	public void onBackPressed() 
	{
		// TODO Auto-generated method stub
		
		 new AlertDialog.Builder(TabMain.this)
        .setTitle( "Exit Application" )
        .setMessage( "Are you sure you want to Exit" )
        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface arg0, int arg1) 
            {
                //do stuff onclick of YES
            	finish();
            }

			public void onClick(View v) 
			{
				// TODO Auto-generated method stub  
			}
        })
        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() 
         {
          	public void onClick(DialogInterface arg0, int arg1)
            {
            	//do stuff onclick of CANCEL
            	arg0.dismiss();
            }
            
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
			}
			
        }).show();
	}
	
	Runnable getPersonalInfo=new Runnable()
	{		
		public void run() 
		{ 
			try
			{
				
		      String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+
							 	AppData.getUserInfo().getpublickey() ));
			  String URL=AppData.hostURL+"/WebService/iTopUp/csrapp.php/GetPersonalInfo/LoginId/"+AppData.getUserInfo().getLoginID()
                         +"/Checksum/"+checksum;
              
			  System.out.println("URL===>\n"+URL);
              String response=httpConn.createHttpConn(URL);
              System.out.println("Response:"+response);
              myAccountInfo=new MyAccountInfo();
              final JSONObject jsonObject=new JSONObject(response);

              if(jsonObject.getString("ResponseCode").equals("000"))
              {
            	  if(jsonObject.has("Balance"))
                      myAccountInfo.setBalance(""+Integer.parseInt(jsonObject.getString("Balance"))/100);
                 else
                     myAccountInfo.setBalance("Not Available");


                 System.out.println("========="+
                                    "\nBalance:"+myAccountInfo.getBalance());
                 handler.post(new Runnable()
                 { 
						public void run() 
						{
							// TODO Auto-generated method stub
							Toast.makeText(TabMain.this,"Your Current Balance is "+myAccountInfo.getBalance()+ ".",Toast.LENGTH_SHORT).show();
							pd.dismiss();
							tabHost.setCurrentTab(0);
						}
                 }); 
                   
              }
              else
              {
            	  handler.post(new Runnable()
            	  {
					
					public void run() 
					{
						// TODO Auto-generated method stub
						pd.dismiss();
						try 
						{
							Toast.makeText(TabMain.this,jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
						}
						
						catch (JSONException e) 
						{
							e.printStackTrace();
						}
					}
				});
              }

			}//try
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	};//getpersonalInfo
}
    
